package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"novel-hub/models/cache"
	"novel-hub/models/mysql"
	"novel-hub/novelrpc/internal/svc"
	"novel-hub/novelrpc/novelrpc"
	"novel-hub/pkg"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *novelrpc.LoginRequest) (*novelrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User

	if in.TypeLogin == 1 || in.TypeLogin == 2 || in.TypeLogin == 3 || in.TypeLogin == 4 {
		if err := user.FindUserByPhone(mysql.DB, in.Phone); err != nil {
			return nil, errors.New("手机号不存在")
		}
		if in.TypeLogin == 1 {
			user = mysql.User{
				Phone:     in.Phone,
				Password:  pkg.Md5(in.Password),
				AvatarUrl: "https://cn.bing.com/images/search?q=%e5%9b%be%e7%89%87&id=C5199094A88719FACE98CCC7EFFF652DF892E23B&FORM=IACFIR",
				Nickname:  fmt.Sprintf("作者%d%d", time.Now().Unix(), rand.Intn(10000)),
			}
			if err := user.UserAdd(mysql.DB); err != nil {
				return nil, errors.New("注册失败")
			}
		}
		if in.TypeLogin == 2 {
			if user.Password != pkg.Md5(in.Password) {
				return nil, errors.New("密码错误")
			}
		}
		if in.TypeLogin == 3 {
			result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Phone).Result()
			if result != in.SendSmsCode {
				return nil, errors.New("验证码错误")
			}
		}
		if in.TypeLogin == 4 {
			result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Phone).Result()
			if result != in.SendSmsCode {
				return nil, errors.New("验证码错误")
			}
			user.Password = pkg.Md5(in.Password)
			if err := user.UpdatePassword(mysql.DB, in.Phone); err != nil {
				return nil, errors.New("密码修改失败")
			}
		}
	}

	return &novelrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
